package com.ruoyi.web.qualityController;

import cn.hutool.core.collection.IterUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.List;
import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.quality.ProjectSetting;
import com.ruoyi.system.domain.quality.QualityDefectProject;
import com.ruoyi.system.domain.quality.QualityDefectSetting;
import com.ruoyi.system.mapper.ProjectSettingMapper;
import com.ruoyi.system.mapper.QualityDefectProjectMapper;
import com.ruoyi.system.mapper.QualityDefectSettingMapper;
import com.ruoyi.system.service.IQualityDefectSettingService;
import com.ruoyi.system.service.IQualityDefectTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 检验标准设置Controller
 *
 * @author tangjie
 * @date 2023-03-08
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
        @Api(tags ="检验标准设置")
    @RestController
@RequestMapping("/quality/setting" )
public class QualityDefectSettingController extends BaseController {

    private final IQualityDefectSettingService iQualityDefectSettingService;

    @Resource
    private QualityDefectSettingMapper qualityDefectSettingMapper;

    @Autowired
    private IQualityDefectTypeService iQualityDefectTypeService;

    @Resource
    private ProjectSettingMapper projectSettingMapper;

    @Resource
    private QualityDefectProjectMapper qualityDefectProjectMapper;

    /**
     * 查询检验标准设置列表
     */
    //@PreAuthorize("@ss.hasPermi('quality:setting:list')")
    @GetMapping("/list")
        @ApiOperation(value = "查询检验标准设置列表")
        public TableDataInfo list(QualityDefectSetting qualityDefectSetting)
    {
        startPage();
        LambdaQueryWrapper<QualityDefectSetting> lqw = new LambdaQueryWrapper<QualityDefectSetting>();
        if (qualityDefectSetting.getMaterialId() != null){
            lqw.eq(QualityDefectSetting::getMaterialId ,qualityDefectSetting.getMaterialId());
        }
        if (qualityDefectSetting.getCheckScene()!=null){
            lqw.eq(QualityDefectSetting::getCheckScene ,qualityDefectSetting.getCheckScene());
        }
        if (StringUtils.isNotBlank(qualityDefectSetting.getCode())){
            lqw.like(QualityDefectSetting::getCode ,qualityDefectSetting.getCode());
        }
        if (StringUtils.isNotBlank(qualityDefectSetting.getName())){
            lqw.like(QualityDefectSetting::getName ,qualityDefectSetting.getName());
        }
        if (StringUtils.isNotBlank(qualityDefectSetting.getCheckSceneName())){
            lqw.apply("b.dict_value like '%"+qualityDefectSetting.getCheckSceneName()+"%'");
        }
        if (StringUtils.isNotBlank(qualityDefectSetting.getMaterialName())){
            lqw.apply("c.material_name like '%"+qualityDefectSetting.getMaterialName()+"%'");
        }

        List<QualityDefectSetting> list = qualityDefectSettingMapper.listByParam(lqw);
        return getDataTable(list);
    }

    /**
     * 导出检验标准设置列表
     */
    //@PreAuthorize("@ss.hasPermi('quality:setting:export')" )
    @Log(title = "检验标准设置" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
                @ApiOperation(value = "导出检验标准设置列表")
            public AjaxResult export(QualityDefectSetting qualityDefectSetting) {
        LambdaQueryWrapper<QualityDefectSetting> lqw = new LambdaQueryWrapper<QualityDefectSetting>(qualityDefectSetting);
        List<QualityDefectSetting> list = iQualityDefectSettingService.list(lqw);
        ExcelUtil<QualityDefectSetting> util = new ExcelUtil<QualityDefectSetting>(QualityDefectSetting. class);
        return util.exportExcel(list, "setting" );
    }

    /**
     * 获取检验标准设置详细信息
     */
    //@PreAuthorize("@ss.hasPermi('quality:setting:query')" )
    @GetMapping(value = "/{id}" )
                @ApiOperation(value = "获取检验标准设置详细信息")
            public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        List<Long> collect = projectSettingMapper.selectList(new QueryWrapper<ProjectSetting>().lambda().eq(ProjectSetting::getSettingId, id)).stream().map(ProjectSetting::getProjectId).collect(Collectors.toList());
        if(IterUtil.isEmpty(collect)){
            return AjaxResult.success(Lists.newArrayList());
        }
        LambdaQueryWrapper<QualityDefectProject> lqw = new LambdaQueryWrapper<QualityDefectProject>();
        lqw.in(QualityDefectProject::getId,collect);
        List<QualityDefectProject> list = qualityDefectProjectMapper.listByParam(lqw);
        return AjaxResult.success(list);
    }

    /**
     * 新增检验标准设置
     */
    //@PreAuthorize("@ss.hasPermi('quality:setting:add')" )
    @Log(title = "检验标准设置" , businessType = BusinessType.INSERT)
    @PostMapping
                @ApiOperation(value = "新增检验标准设置")
    @Transactional
   public AjaxResult add(@RequestBody QualityDefectSetting qualityDefectSetting) {

        qualityDefectSetting.getProjectIdList().stream().forEach(ii->{
            QualityDefectSetting qualityDefectSetting1 = qualityDefectSettingMapper.selectOne(new QueryWrapper<QualityDefectSetting>().lambda().eq(QualityDefectSetting::getMaterialId, qualityDefectSetting.getMaterialId()));
            Optional.ofNullable(qualityDefectSetting1).ifPresent(i->{throw new CustomException("该物料检验项目已存在!");});
        });

        iQualityDefectTypeService.checkUnique("quality_defect_setting",qualityDefectSetting.getCode(),null);

        List<Long> projectIdList = qualityDefectSetting.getProjectIdList();
        iQualityDefectSettingService.save(qualityDefectSetting);

        projectIdList.stream().forEach(i->{
            ProjectSetting projectSetting=new ProjectSetting();
            projectSetting.setSettingId(qualityDefectSetting.getId());
            projectSetting.setProjectId(i);
            projectSettingMapper.insert(projectSetting);
        });

        return toAjax( true? 1 : 0);
    }

    /**
     * 修改检验标准设置
     */
    //@PreAuthorize("@ss.hasPermi('quality:setting:edit')" )
    @Log(title = "检验标准设置" , businessType = BusinessType.UPDATE)
    @PutMapping
     @ApiOperation(value = "修改检验标准设置")
    @Transactional
    public AjaxResult edit(@RequestBody QualityDefectSetting qualityDefectSetting) {
        iQualityDefectTypeService.checkUnique("quality_defect_setting",qualityDefectSetting.getCode(),qualityDefectSetting.getId());
        projectSettingMapper.delete(new QueryWrapper<ProjectSetting>().lambda().eq(ProjectSetting::getSettingId,qualityDefectSetting.getId()));
        List<Long> projectIdList = qualityDefectSetting.getProjectIdList();
        projectIdList.stream().forEach(i->{
            ProjectSetting projectSetting=new ProjectSetting();
            projectSetting.setSettingId(qualityDefectSetting.getId());
            projectSetting.setProjectId(i);
            projectSettingMapper.insert(projectSetting);
        });
        iQualityDefectSettingService.updateById(qualityDefectSetting);
        return toAjax(1);
    }

    /**
     * 删除检验标准设置
     */
    //@PreAuthorize("@ss.hasPermi('quality:setting:remove')" )
    @Log(title = "检验标准设置" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
                @ApiOperation(value = "删除检验标准设置")
            public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iQualityDefectSettingService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
